package com.cgs.query.service.impl

import com.cgs.query.domain.ProjectErrorLog
import com.cgs.query.domain.ProjectLockLog
import com.cgs.query.domain.QueryProject
import com.cgs.query.exception.QueryException
import com.cgs.query.service.IProjectErrorLogService
import com.cgs.query.service.IProjectLockLogService
import com.cgs.query.service.jpa.ProjectErrorLogRepository
import com.cgs.query.service.jpa.ProjectLockLogRepository
import kotlinx.coroutines.experimental.launch
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.PageRequest
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
open class ProjectErrorLogServiceImpl : IProjectErrorLogService {

    @Autowired
    private lateinit var errorLogRepository: ProjectErrorLogRepository

    override fun save(projectName: String, callName: String?, e: Exception) {
        errorLogRepository.save(ProjectErrorLog(projectName, callName ?: "unknown", getExceptionMessage(e)
                ?: "未知异常,捕捉信息失败"))
    }

    @Transactional
    override fun deleteByProjectName(projectName: String) {
        errorLogRepository.deleteByProjectName(projectName)
    }

    override fun findByProjectName(name: String, pn: Int, ps: Int): Any? {
        return errorLogRepository.findByProjectNameOrderByTimeDesc(name, PageRequest(pn, ps))
    }

    private fun getExceptionMessage(e: Exception): String? {
        return if (e is QueryException) {
            e.message
        } else {
            if (e.cause == null) {
                e.toString().substring(0, 100)
            } else {
                e.cause!!.message ?: e.cause!!.toString().substring(0, 100)
            }
        }
    }
}
